
const membersModel = require("./models/members");
const koa = require('koa');
const router = require('koa-router')();
const cors = require('koa2-cors');
const bodyParser = require("koa-bodyparser")
const app = new koa();
// 所有数据  有限制显示多少条的功能
router.get("/members",async ctx=>{
    // 示例url：http://localhost:8081/members?offser=0&count=3
    let {offset,count} = ctx.query;  //这里解析出来的是String类型
    var data = await membersModel.find().skip(Number(offset)).limit(Number(count));
    ctx.body = data;
})

// 添加&修改
router.post("/add",async ctx=>{
    let {id,name,age,like} = ctx.request.body;
    // 有id则是修改信息
    if(id){
        await membersModel.findByIdAndUpdate(id,{
            name:name,
            age:age,
            like:like
        })
    }else{
        // 没id是添加信息
        var db = new membersModel({name,age,like,state:false});
        await db.save();
    }
    ctx.redirect("back");
})
// 删除
router.post("/delete",async ctx=>{
    let {id} = ctx.request.body;
    console.log(id);
    await membersModel.remove({_id:id})
})
// 状态更新
router.post("/state",async ctx=>{
    let {id,state} = ctx.request.body;
    console.log(state);
    await membersModel.findByIdAndUpdate(id,{
        state:state
    }, function (err,ret) {
        if(err) {
            console.log('更新失败')
        } else {
            console.log('更新成功')
        }
    })
})


app.use(cors());
app.use(bodyParser());
app.use(router.routes());
app.listen(8081);
console.log("file:///P:/Project/mongo-db/ground-member/index.html");
